//
//  ViewController.h
//  外星球生活圈
//
//  Created by MR.ZHOU on 15/8/12.
//  Copyright (c) 2015年 MR.ZHOU. All rights reserved.
//
#import "DSLocationManager.h"
#import <CoreLocation/CoreLocation.h>

@interface DSLocationManager ()<CLLocationManagerDelegate>
{
    BOOL flag;//用于标记定位成功
}

@property(nonatomic,strong) CLLocationManager *manager;
@property(nonatomic,copy)successLocationBlock sBlock;
@property(nonatomic,copy)failedLocationBlock fBlock;
@end


@implementation DSLocationManager

- (id)init{
    
    if (self = [super init]) {
        
        _manager = [[CLLocationManager alloc]init];
        
        if ([_manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_manager requestAlwaysAuthorization];
            [_manager requestWhenInUseAuthorization];
        }
        
        _manager.delegate = self;

    }
    
    return self;
    
}

+ (DSLocationManager *)shareInstance{
    
    static DSLocationManager *man = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        man = [[DSLocationManager alloc]init];
        
    });
    
    return man;
    
}


#pragma mark --CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    
    if (status == kCLAuthorizationStatusDenied) {
        
        //给一个默认的定位值
        self.fBlock(nil);
        [_manager stopUpdatingLocation];
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //
    if (flag) {
        
        return;
    }
 
    CLLocation *loca = locations.lastObject;
    
    self.sBlock(loca);
    flag = YES;
    [_manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    //给一个默认的定位值
    self.fBlock(error);
    [_manager stopUpdatingLocation];
}

#pragma mark -- block回调

+ (void)getLocationSuccess:(successLocationBlock)success failed:(failedLocationBlock)failed{
    
    [[self shareInstance]getLocationSuccess:success failed:failed];
    
}

- (void)getLocationSuccess:(successLocationBlock)success failed:(failedLocationBlock)failed{

    self.sBlock = success;
    
    self.fBlock = failed;
    
    [_manager startUpdatingLocation];
}
@end
